package finelProject.model;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import finelProject.MyAppConstants;

public class Messages {
	private static int   GeneralMessageId = 0;
	private int MessageId;
	private String   Autor;
	private int 	 RepublishNumber;
	private Timestamp TimeOfPublish;
	private String	 Content;
	private String Topic;
	private int AutorNumberOfFollowers;
	private double popularity;
	private String HtmlTopicVersion;
	
	//Contractor for new messages
	public Messages(String SetAutor, int SetRepublishNumber,Timestamp timeOfPublish2,String SetContent, String setTopic, int SetNumberOfAutorFollowers){
		Autor 	  		= SetAutor;
		RepublishNumber = SetRepublishNumber;
		TimeOfPublish	= timeOfPublish2;
		Content			= SetContent;
		setTopic(setTopic);
		setMessageId(GeneralMessageId++);
		setAutorNumberOfFollowers(SetNumberOfAutorFollowers);
		popularity =  Math.log(2+ SetNumberOfAutorFollowers) * Math.log(2);
	}
	//Contractor for existing messages
	public Messages(String SetAutor, int SetRepublishNumber,Timestamp timeOfPublish2,String SetContent, String setTopic, int SetNumberOfAutorFollowers,int setMessageID,Double setPopularty, String setHTMLContant){
		Autor 	  		= SetAutor;
		RepublishNumber = SetRepublishNumber;
		TimeOfPublish	= timeOfPublish2;
		Content			= SetContent;
		setTopic(setTopic);
		setMessageId(setMessageID);
		setAutorNumberOfFollowers(SetNumberOfAutorFollowers);
		popularity = setPopularty;
		setHtmlTopicVersion(setHTMLContant);
	}

	public String getAutor(){
		return Autor;
	}
	public int getRepublishNumber(){
		return RepublishNumber;
	}
	public Timestamp getTimeOfPublish(){
		return TimeOfPublish;
	}
	public String getContant(){
		return Content;
	}
	public void setContant(String setContant){
		Content = setContant;
	}
	public void setRepublishNumber(int SetRepublishNumber){
		RepublishNumber = SetRepublishNumber;
	}
	public String getTopic() {
		return Topic;
	}
	public void setTopic(String topic) {
		Topic = topic;
	}
	public int getAutorNumberOfFollowers() {
		return AutorNumberOfFollowers;
	}
	public void setAutorNumberOfFollowers(int autorNumberOfFollowers) {
		AutorNumberOfFollowers = autorNumberOfFollowers;
	}
	public int getMessageId() {
		return MessageId;
	}
	public void setMessageId(int messageId) {
		MessageId = messageId;
	}
	public double getPopularity() {
		return popularity;
	}
	public void setPopularity(double popularity) {
		this.popularity = popularity;
	}
	public String parseContent(String text, ServletContext  servletContext ,HttpServletResponse response){
		
		if ((text.equals(null)) || text.length() == 0) return text;
  	  
  	  String retext = text;
  	  String match;
  	  String sfxStr;
  	  String prfxStr;
	  String OpeningSpan = "<a class=\"highlight\"  style=\"cursor: pointer;\" href=\"topic.html?topic=";
	  String MiddleSpan  ="\">";
	  String OpeningSpan2 = "<a class=\"highlight2\"  style=\"cursor: pointer;\" href=\"MyProfile.html?profile=";
	  String ClosingSpan = "</a>";
	  Boolean UserExist = false;
  	 
  	  
  	//find the place of the topic in the message
  	  int topicStartIndex = text.indexOf('#');
  	  int topicEndIndex   = text.indexOf(' ',topicStartIndex);
  	  
		//find the place of the reply/mention
  	  int mentionStartIndex = text.indexOf('@');
  	  int mentionEndIndex   = text.indexOf(' ',mentionStartIndex);
  	  
  	  if((topicStartIndex != -1) || (mentionStartIndex != -1)){
  		  if(topicStartIndex != -1){  
  			  //highlight the topic 
  			  prfxStr = text.substring(0,topicStartIndex);
  			  if(topicEndIndex == -1){
  				  match = text.substring(topicStartIndex,text.length());

  				  retext = prfxStr + OpeningSpan + match.substring(1) + MiddleSpan + match + ClosingSpan;
  			  }else{
  				  match = text.substring(topicStartIndex,topicEndIndex);
  				  sfxStr = text.substring(topicEndIndex, text.length());
  				  retext = prfxStr + OpeningSpan + match.substring(1) + MiddleSpan + match + ClosingSpan + sfxStr;
  			  }
  			  
  		  }
  		  if(mentionStartIndex != -1){
  			  
  			//highlight the reply/mention
  			  int startIndex = 0, searchStrLen = 1;
  			  int index;
  			  int spaceIndex;
  			  while ((index = retext.indexOf('@', startIndex)) > -1) {
  				  
  			       spaceIndex =  retext.indexOf(' ',index);
  			       if(spaceIndex == -1){
  			    	   if(retext.indexOf('@',index+1)> -1){
  			    		   spaceIndex = retext.indexOf('@',index+1);
  			    	   }else{
  			    		   spaceIndex = retext.length();
  			    	   }
  			    	 
  			    	   prfxStr = retext.substring(0,index);
  			    	   match   = retext.substring(index,spaceIndex);
  			    	   sfxStr  = retext.substring(spaceIndex,retext.length());
  			    	   
  			       }else{
  			    	   prfxStr = retext.substring(0,index);
  			    	   match   = retext.substring(index,spaceIndex);
  			    	   sfxStr  = retext.substring(spaceIndex,retext.length());
  			       }
  			       
  			       
  			     try{
  					//obtain UserDB data source from Tomcat's context
  					Context context = new InitialContext();
  					BasicDataSource ds = (BasicDataSource)context.lookup(MyAppConstants.DB_DATASOURCE);
  					Connection conn = ds.getConnection();
  					
  					
  					//get the current user's Username
  					String Username = match.substring(1);
  					
  					try {
  						//searching for all the users who the current user follow
  						PreparedStatement stmt;
  						stmt = conn.prepareStatement(MyAppConstants.GET_USER);
  						stmt.setString	 (1, Username);
  					
  						//return users instances of the users who the current user follow.
  						ResultSet rs = stmt.executeQuery();
  						if(rs.next()){
  							UserExist = true;
  						}else{
  							UserExist = false;
  						}
  						rs.close();
  						stmt.close();
  						
  					} catch (SQLException e) {
  						servletContext.log("Error while querying for customers", e);
  			    		try {
							response.sendError(500);
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}//internal server error
  					}
  					conn.close();
  					
  					
  				
  				}catch(SQLException | NamingException e){
  					servletContext.log("Error while closing connection", e);
  		    		try {
						response.sendError(500);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}//internal server error
  				} 
  			       if( UserExist){
  			    	   if(spaceIndex == retext.length()){
  			    		   retext = prfxStr + OpeningSpan2 + match.substring(1) + MiddleSpan + match + ClosingSpan;
  			    	   }else{
  			    		   retext = prfxStr + OpeningSpan2 + match.substring(1) + MiddleSpan + match + ClosingSpan + sfxStr;
  			    	   }
  			       
  			    	   startIndex = index + searchStrLen + 77 + 2*match.length()-1;
  			       }else{
  			    	   startIndex = index + searchStrLen;
  			       }
  			  }
  		  }
  	  return retext;
  	}else{
  		return text;
  	}
    
		
		
		
	}
	public String getHtmlTopicVersion() {
		return HtmlTopicVersion;
	}
	public void setHtmlTopicVersion(String htmlTopicVersion) {
		HtmlTopicVersion = htmlTopicVersion;
	}
}

